package org.glut.saltedfish.filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;

/**
 * 登录验证过滤器
 * 用于保护需要登录才能访问的资源
 */
// @WebFilter("/*")
public class LoginFilter implements Filter {
    
    private static final Logger logger = Logger.getLogger(LoginFilter.class);
    
    // 不需要登录验证的URL列表
    private static final List<String> EXCLUDE_URLS = Arrays.asList(
        "/login",
        "/sign", 
        "/checkLogin",
        "/logout",
        "/products",
        "/index.html",
        "/static/",
        "/css/",
        "/js/",
        "/images/",
        "/favicon.ico"
    );

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        logger.info("LoginFilter 初始化完成");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        
        String requestURI = httpRequest.getRequestURI();
        String contextPath = httpRequest.getContextPath();
        String path = requestURI.substring(contextPath.length());
        
        logger.debug("请求路径: " + path);
        
        // 检查是否是不需要登录验证的URL
        if (isExcludeUrl(path)) {
            chain.doFilter(request, response);
            return;
        }
        
        // 检查用户是否已登录
        HttpSession session = httpRequest.getSession(false);
        if (session != null && session.getAttribute("user") != null) {
            // 用户已登录，继续处理请求
            chain.doFilter(request, response);
        } else {
            // 用户未登录，返回401错误
            logger.warn("用户未登录，拒绝访问: " + path);
            httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            httpResponse.setContentType("application/json;charset=utf-8");
            
            try (PrintWriter out = httpResponse.getWriter()) {
                out.write("{\"code\":401,\"msg\":\"请先登录\"}");
            }
        }
    }
    
    /**
     * 检查URL是否在排除列表中
     * @param path 请求路径
     * @return 是否排除
     */
    private boolean isExcludeUrl(String path) {
        for (String excludeUrl : EXCLUDE_URLS) {
            if (path.equals(excludeUrl) || path.startsWith(excludeUrl)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void destroy() {
        logger.info("LoginFilter 销毁");
    }
}